package save;

import java.util.List;
import java.util.Map;

import fj.data.Option;
import global.Global;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.Initialize;
import server.db.StmtHelper;

import ajaxmethods.SessionMethod;

public class HasForm extends SessionMethod {

	private String size = "";
	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response) {
		super.perform(request, response);
		Global global = new Global(request);
		
		if(global.isLoggedIn.f(request))
		{
		try {
			List<Map<String,String>> map = StmtHelper.db("select * from form where iduser=").addVariable(global.getUser().id).collectIntoMaps.unsafeGet();
			if(map!=null && map.size()>0)
				size=String.valueOf(map.size());
			else
				size = "0";
			
				StringBuffer sb = new StringBuffer();
				sb.append("<div id=\"formsTable\">");
				sb.append("<div class=\"headerCols\">");
				sb.append("<div style=\"width:132px;\" class=\"col\">Form Name</div>");
				sb.append("<div class=\"col\">Title</div>");
				sb.append("<div class=\"col\"># Views</div>");
				sb.append("<div class=\"col\"># Submissions</div>");
				sb.append("<div class=\"col\">Code</div>");
				sb.append("<div style=\"width:80px;\" class=\"col\">Remove</div>");
				//close headerCols
				sb.append("</div><div class=\"verticalscroll\"><div class=\"items\"><div class=\"section\">");
			if(map!=null)
			{
				for(int i = 0;i < map.size(); i++)
				{
					if(i>0&&i%7==0)
						sb.append("</div><div class=\"section\">");
					Map<String,String> formMap = map.get(i);
					sb.append("<div id=\""+formMap.get("idform")+"\" class=\"row\"><div class=\"codecontent\" style=\"display:none;\">"+formMap.get("content")+"</div>");
					sb.append("<div class=\"rowitem\" style=\"width:128px;text-align:left;\"><img class=\"editformname\" src=\""+Initialize.appURL()+"/images/icons/edit.png\"></img><a class=\"editformname\">"+Option.fromString(formMap.get("formname")).orSome("Name Your Form")+"</a>" +
							"<div style=\"display:none;\" class=\"textbox\"><input class=\"esoinput\" maxlength=\"35\" id=\"formname\">" +
							"<button style=\"width:42px;\" name=\"submit\">save</button><button style=\"width:52px;\" name=\"cancel\">cancel</button></div></div>");
					sb.append("<div class=\"rowitem\">"+Option.fromString(formMap.get("title")).orSome("")+"</div>");
					sb.append("<div class=\"rowitem\">"+Option.fromString(formMap.get("views")).orSome("")+"</div>");
					sb.append("<div class=\"rowitem\">"+formMap.get("submissions")+"</div>");
					sb.append("<div class=\"rowitem\"><div extraheight=\"205\" class=\"codeBubble\" id=\"detailview\"><a id=\""+formMap.get("idform")+"\" class=\"detailLink moredetails\">Get Code</a></div></div>");
					sb.append("<div style=\"width:80px;\" class=\"rowitem\"><img extraheight=\"130\" class=\"delete\" src=\""+Initialize.appURL()+"/images/icons/delete.png\"/></div>");
					sb.append("</div>");
				}
			}	
				sb.append("</div>");
				//close formsTable
				sb.append("</div></div></div>");
				
				sb.append(javascriptOut());
				if(map!=null && map.size()>0)
					data.put("hasAForm", true);
				data.put("hasForm", sb.toString()).write(response.getWriter());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		
	}

	private StringBuffer javascriptOut() {
		StringBuffer sb = new StringBuffer();
		sb.append("<script>");
		sb.append("$(document).ready(function() {" +
				"$('#scrollForms .verticalscroll').scrollable({vertical:true,pagingtable:true,tablesize:7,next:'#myforms #action .next',prev:'#myforms #action .prev'," +
				"onSeek:function(){" +
				"if(this.getIndex()==0)" +
				"	this.getItemWrap().css('top',0);" +
				"var size = this.getRowItems().size();\n" +
					"$('#action #start').html(parseInt(7*this.getIndex())+1);" +
					"$('#action #end').html(Math.min(size,parseInt(7*this.getIndex())+7));" +
					"if(size<=7)" +
					"	$('#myforms #action .next').addClass('disabled');" +
		" }}).data('scrollable').seekTo(0);" +
		
		"if($('#scrollForms .verticalscroll').data('scrollable').getRowItems().size()==0) {" +
		"	$('#noobjectsfound').show().next().hide();" +
		"	console.log('no objects found');" +
		"}" +
		"$('#myforms #action #displaynumobjects #total').html("+size+");" +
		"$('.editformname').unbind('click').click(function(){var elem = $(this);$('.rowitem .textbox').hide().prev().show();elem.siblings('.textbox').show().find('input').val(elem.parent().find('a.editformname').hide().html()).select(); });" +
		"$('button[name=\"submit\"],button[name=\"cancel\"]').unbind('click').click(function(){\n" +
		"var button=$(this);" +
		"if(button.attr('name')=='submit') {" +
		"	var newtitle = $(this).prev().val();" +
		"	$.post('"+Initialize.appURL()+"/ajaxCall.jsp?do=save.UpdateForm',{idform:button.parent().parent().parent().attr('id'),formname:newtitle}," +
				"function(data){" +
				"button.parent().prev().html(newtitle).show();" +
				"$('.rowitem .textbox').hide();" +
				"});" +
		"}" +
		"else {" +
		"	$('.rowitem .textbox').hide();" +
		"	button.parent().prev().show();" +
		"}});" +
		"$('#formsTable').bubble({popupItemSelector:'#formsTable .codeBubble',bubbleselector:'formbubble'," +
		"autoclose:true,onOpen:function(){" +
		"	$('textarea#formCode').text($('#'+$(this).find('a').attr('id')+' .codecontent').html());" +
		"}}).data('formbubble').resize(240,155).setBody('<textarea class=\"esotextarea\" style=\"height:80px;width:212px;\" id=\"formCode\" ></textarea><p>Embed this code in your website to generate leads</p>');" +
		"$('#formsTable').bubble({popupItemSelector:'#formsTable img.delete',bubbleselector:'deletebubble',autoclose:true," +
		"onOpen:function() {" +
		"		}}).data('deletebubble').resize(200,110).setBody('<p>Are you sure you want to permanently remove this form?</p><button id=\"deleteform\" onclick=\"deleteForm($(this));\" class=\"esobutton\">Yes</button><button onclick=\"closeDeleteBubble();\" class=\"esobutton\">No</button>');" +
		"$('.rowitem .delete').click(function(){var deleteImg = $(this);$('button#deleteform').attr('idform',deleteImg.closest('.row').attr('id'));});" +
		"$('#formsTable .verticalscroll .row').hover(function(){$('#noscrollsidepanel .formsmall').html($(this).find('.codecontent').html());},function(){$('#noscrollsidepanel .formsmall').children().remove();});" +
		"});");
		sb.append("function deleteForm(button) {\n" +
				"var id = button.attr('idform');" +
				"	$.post('"+DeleteForm.url()+"',{idform:id},"+
				"function(data){" +
				"var scrollAPI = $('#scrollForms .verticalscroll').data('scrollable');" +
				"$('#formsTable .row#'+id).slideToggle(function(){scrollAPI.deleteItem(this);});\n" +
				"$('#formsTable').data('deletebubble').close();" +
				"var total = $('#myforms #action #displaynumobjects #total');total.html(total.html()-1); " +
				"if(parseInt(total.html())==0) " +
				"	$('#noobjectsfound').show().next().hide();" +
				"var end = $('#displaynumobjects #end'); if(parseInt(end.html())>parseInt(total.html())) end.html(total.html());" +
				"var start = $('#displaynumobjects #start'); " +
				"if(parseInt(start.html()) > parseInt(end.html())) {start.html(end.html());}" +
				"});" +
				"}");
		sb.append("function closeDeleteBubble() {$('#formsTable').data('deletebubble').close();}");
		sb.append("</script>");
		return sb;
	}

}
